package utils

import (
	"encoding/json"
	"fmt"
	"github.com/golang/protobuf/proto"
	"grpc.getaway.adminspro.padmins.com/internal/api/utils/rpc"
	"reflect"
	"time"
)

type Message struct {
	Code      int         `json:"code"`
	Msg       string      `json:"msg"`
	Data      interface{} `json:"data"`
	Runtime   string      `json:"runtime"`
	startTime time.Time
}

func (m *Message) SetStartTime(startTime time.Time) *Message {
	m.startTime = startTime
	return m
}

func (m *Message) JSON(code int, msg string, data interface{}) string {
	m.Code = code
	m.Msg = msg

	if data != nil && (reflect.ValueOf(data).Kind() == reflect.Struct || !reflect.ValueOf(data).IsNil()) {
		if d, ok := data.(proto.Message); ok {
			m.Data = rpc.ProtoMessageToMap(d) // 防止json中返回null值
		} else {
			m.Data = data
		}
	} else {
		m.Data = map[string]string{}
	}
	m.Runtime = fmt.Sprintf("%v", time.Since(m.startTime))

	jsonString, e := json.MarshalIndent(m, "", "  ")

	if e != nil {
		m.Code = 500
		m.Msg = e.Error()
		m.Data = map[string]string{}
		jsonString, _ = json.MarshalIndent(m, "", "  ")
	}

	return string(jsonString)
}
